package com.example.zhu29.bledemo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhu29.bledemo.Contast;
import com.example.zhu29.bledemo.R;
import com.example.zhu29.bledemo.interFace.IBleConnectStatusListener;
import com.example.zhu29.bledemo.interFace.IBleIndicateListener;
import com.example.zhu29.bledemo.interFace.IBleScanListener;
import com.example.zhu29.bledemo.interFace.IBleStateListener;
import com.example.zhu29.bledemo.interFace.IBleWriteListener;
import com.example.zhu29.bledemo.interFace.IPermissionsListener;
import com.example.zhu29.bledemo.util.ZBleManager;
import com.example.zhu29.bledemo.util.ZDataUtil;
import com.example.zhu29.bledemo.util.ZDigitalTransTool;
import com.example.zhu29.bledemo.util.ZHexUtil;
import com.example.zhu29.bledemo.util.ZPermissionUtil;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchResult;
import com.trello.rxlifecycle2.components.RxActivity;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/12/12.
 * Blood pressure device bluetooth status
 */

public class SocketPressureActivity extends RxActivity implements View.OnClickListener, IPermissionsListener, IBleStateListener {

    private TextView tvContent;
    private TextView tvStart;
    private TextView tvEnd;
    private TextView tvStatus;
    private TextView tvSn;
    private TextView tvProcess;
    private TextView tvContentDataArray;
    private ProgressBar progress;
    private SearchResult mDevice;
    private String mType = "";
    private String content = "";
    private String mSnNumber;
    private View tvBeginPressure;
    private ZBleManager mBleManager;
    private int version_code = 2;
    private String result;
    private boolean getResult;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_pressure);
        findID();
        getIntents();
//        initScan();
        initListener();
        requestPermission();
    }

    private void initScan() {
        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);
    }

    private void requestPermission() {
        if (!ZPermissionUtil.getInstance().isPermissions(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            ZPermissionUtil.getInstance().requestPermissions(this, this, Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            initBleSetting();
        }
    }

    private void initListener() {
        tvStart.setOnClickListener(this);
        tvBeginPressure.setOnClickListener(this);
        tvEnd.setOnClickListener(this);
    }

    private void connect() {
        mBleManager.connect(mDevice.getAddress(), new IBleConnectStatusListener() {
            @Override
            public void onStartConnect() {
                tvStatus.setText(R.string.start_connect);
                progress.setVisibility(View.VISIBLE);
            }

            @Override
            public void onConnectFail() {
                tvStatus.setText(R.string.connect_failed);
                progress.setVisibility(View.GONE);
                isConnect = false;
                isEnableGetValue = false;
            }

            @Override
            public void onConnectSuccess(int code, BleGattProfile data, String mac) {
                progress.setVisibility(View.GONE);
                tvStatus.setText(R.string.connect_success);

                if (!isEnableGetValue)
                    indicate();
                isConnect = true;
                isNeedSend = true;
                isEnableGetValue = true;
            }

            @Override
            public void onDisConnected(String mac) {
                if (isConnect) {
                    tvStatus.setText(R.string.connect_cancel);
                    progress.setVisibility(View.GONE);
                    isConnect = false;
                    isEnableGetValue = false;
                }
            }
        });
    }

    /**
     * @param data "3.0" protocol "00" package length:18
     * @param data "2.0" protocol "00" package length:15
     */
    private void getBleInfo(byte[] data) {
        if (null == data) return;
        if (data.length != 18 && data.length != 15) return;
        byte index0 = data[0];
        if (index0 != 85) return;
        byte index2 = data[2];
        if (index2 != 0) return;
        if (data.length != 18) return;
        //sn
        byte[] snArray = new byte[9];
        System.arraycopy(data, 8, snArray, 0, 9);
        mSnNumber = ZDigitalTransTool.bytetoString(snArray);
        byte index4 = data[4];
        //品牌
        mType = getTypeStr(index4);
        Log.e("getBleInfo: ", String.format("\nSN号:%s---客户码:%s", mSnNumber, mType));
        tvSn.setText(String.format("SN号:%s; 客户码:%s", mSnNumber, mType));
    }

    private String getTypeStr(byte type) {
        String typeStr = "";
        if (type == 0) {
            typeStr = getString(R.string.apple);
        } else if (type == 1) {
            typeStr = getString(R.string.bioland);
        } else if (type == 2) {
            typeStr = getString(R.string.haier);
        } else if (type == 3) {
            typeStr = getString(R.string.bioland);
        } else if (type == 4) {
            typeStr = getString(R.string.xiaomi);
        } else if (type == 5) {
            typeStr = getString(R.string.daotong);
        } else if (type == 6) {
            typeStr = "KANWEI";
        }
        return typeStr;
    }

    /**
     * 向蓝牙发送写入数据
     * Send write data to bluetooth
     *
     * @param data 写入的byte数据(The byte data that was written)
     */
    @SuppressLint("CheckResult")
    private void write(final String mac, final byte[] data) {
        mBleManager.write(mac, Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_WRITEABLE, data, new IBleWriteListener() {
                    @Override
                    public void onWriteSuccess() {
                        Log.e("zdw", getString(R.string.write_data_ok) + Arrays.toString(data));
                    }

                    @Override
                    public void onWriteFailure(int code) {
                        Log.e("zdw", getString(R.string.write_data_error) + Arrays.toString(data));
                    }
                });
    }

    /**
     * 订阅接受广播通知
     * Subscribe to receive broadcast notifications
     */
    private void indicate() {
        mBleManager.indicate(mDevice.getAddress(), Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_READABLE, new IBleIndicateListener() {
                    @Override
                    public void onIndicateSuccess() {
                        result = "";
                        flag = true;
                        getResult = false;
                        Log.e("zdw", getString(R.string.indicate_success));
                        try {
                            Thread.sleep(500L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        byte[] data_00 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(0));
                        refreshLogView("写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_00, data_00.length))));


                        write(mDevice.getAddress(), data_00);
//                        write(mDevice.getAddress(), ZHexUtil.hexStringToBytes("5A0A001005020F213BE8"));

                    }

                    @Override
                    public void onIndicateFailure(int code) {
                        Log.e("zdw", getString(R.string.indicate_failure));
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e("zdw", getString(R.string.get_device_data) + Arrays.toString(data));
                        refreshLogView("\n血压计返回：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data, data.length))));
//                        getData(data);
                        //解析
                        if (data.length > 3) {
                            if (data[2] != 0)
                                getValueData3(data);
                            else {
                                getBleInfo(data);
                            }
                        }
                    }
                });
    }

    /**
     * 更新显示收发的数据
     *
     * @param msg
     */
    void refreshLogView(String msg) {
        tvContentDataArray.append(msg);
        int offset = tvContentDataArray.getLineCount() * tvContentDataArray.getLineHeight();
        if (offset > tvContentDataArray.getHeight()) {
            tvContentDataArray.scrollTo(0, offset - tvContentDataArray.getHeight());
        }
    }

    void appendContent(String msg) {
        tvContent.append(msg);
        int offset = tvContent.getLineCount() * tvContent.getLineHeight();
        if (offset > tvContent.getHeight()) {
            tvContent.scrollTo(0, offset - tvContent.getHeight());
        }
    }


    @SuppressLint("StringFormatMatches")
    private void showContent(byte[] data) {
        if (data.length != 14) return;
        byte index2 = data[2];
        if (index2 != 3) return;//only get 03 package
        byte index9 = data[9];
        byte index10 = data[10];//9-10 is SYS
        byte index11 = data[11];//DIA
        byte index12 = data[12];//heart rate
        tvContent.setText(String.format(getString(R.string.bp_result), index9 + index10, index11, index12));
    }

    /**
     * 这里处理结果包显示
     * The processing results are shown here
     */
    private void getData(byte[] data) {
        if (null == data) return;
        if ((data.length > 2 && data[2] == 3) || (data_temp.length > 2 && data_temp[2] == 3)) {
            if (data.length == 14) {
                showContent(data);
            } else {
                if (data_temp.length < 14) {
                    //如果加起来长度还是不够，就直接拼接
                    if (data_temp.length + data.length < 14) {
                        data_temp = byteMerger(data_temp, data);
                    }
                    //如果加起来长度刚好够了，
                    else if (data_temp.length + data.length == 14) {
                        data_temp = byteMerger(data_temp, data);
                        Log.e("zdw007", "length：" + length + "data_temp：" + Arrays.toString(data_temp));
                        showContent(data_temp);
                        data_temp = null;
                        data_temp = new byte[]{};
                    }
                }
            }

        }
    }


    private void getIntents() {
        Intent intent = getIntent();
        mDevice = intent.getParcelableExtra("device");
    }

    private void findID() {
        tvContent = findViewById(R.id.tv_content);
        tvProcess = findViewById(R.id.tv_process);
        tvSn = findViewById(R.id.tv_sn);
        tvStart = findViewById(R.id.tv_start);
        tvEnd = findViewById(R.id.tv_end_pressure);
        tvBeginPressure = findViewById(R.id.tv_start_pressure);
        tvStatus = findViewById(R.id.tv_status);
        progress = findViewById(R.id.progress);
        tvContentDataArray = findViewById(R.id.tv_content_data_array);
        tvContentDataArray.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    //java 合并两个byte数组
    private byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
        byte[] byte_3 = new byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

    private String mHighValue, mmLowValue, mHeratValue;
    byte[] data_temp = new byte[]{};
    int length = 8;
    boolean flag = true;

    private void getValueData3(byte[] data) {
        if (null == data) return;
        if (data.length < 3) return;
        byte index2 = data[2];
        //[85, 5, -18, 1, 75]
        switch (index2) {
            case 2:
                if (data.length != 8) break;
                setPreValue(data);
                break;
            case 3:
                if (data.length != 14) break;
                try {

                    byte index3 = data[3];//Year
                    byte index4 = data[4];//Month
                    byte index5 = data[5];//Day
                    byte index6 = data[6];//Hour
                    byte index7 = data[7];//Minute
                    byte index8 = data[8];//00和01为当前结果，02以上为历史记忆
                    byte[] valueArr = {data[10], data[9]};
                    String date = String.format("20%s-%s-%s %s:%s："
                            , String.format("%02d", (int) index3), String.format("%02d", (int) index4), String.format("%02d", (int) index5),
                            String.format("%02d", (int) index6), String.format("%02d", (int) index7));
                    String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                    mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                    mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data[11]}), 16));//低压
                    mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data[12]}), 16));//低压

                    String result_temp = date + String.format(getString(R.string.bp_result), mHighValue, mmLowValue, mHeratValue);

                    //延迟300ms发送03包读取历史记忆
                    Flowable.timer(300, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(bindToLifecycle())
                            .subscribe(new Consumer<Object>() {
                                @Override
                                public void accept(Object o) throws Exception {
                                    byte[] data_03 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(3));
                                    refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_03, data_03.length))));
                                    write(mDevice.getAddress(), data_03);
                                }
                            });
                    //00和01是当前结果，否则为历史记忆
                    if (index8 == 0 || index8 == 1) {
                        if (!getResult) {
                            tvContent.setText("");
                            appendContent("当前结果：" + result_temp);
                            getResult = true;
                        }
                    } else {
                        appendContent("\n历史记忆：" + result_temp);
                    }
//                    if (flag) {
//                        tvContent.setText("");
//                        appendContent(result);
//                    } else
//                        appendContent("\n" + result);
                    flag = false;
                } catch (Exception e) {
                    Log.e("zdw007", e.toString());
                }
                break;
            case -18:
                if (data.length != 5) break;
                Toast.makeText(this, R.string.error_hint, Toast.LENGTH_SHORT);
                flag = false;
                getResult = false;
                break;
        }
    }

    private void getValueData2(byte[] data) {
        if (null == data) return;

        //先判断是过程包还是结果包
        if (data_temp.length < 3) {
            data_temp = byteMerger(data_temp, data);
            if (data_temp.length > 2) {
                byte index2 = data_temp[2];
                //[85, 5, -18, 1, 75]
                switch (index2) {
                    case 2:
                        length = 8;
                        break;
                    case 3:
                        length = 14;
                        break;
                    case -18:
                        length = 5;
                        break;
                }
                //如果加起来长度刚好够了，
                if (data_temp.length == length) {
                    switch (length) {
                        case 8:
                            //过程包
                            setPreValue(data_temp);
                            break;
                        case 14:
                            //结果包
                            try {
                                byte[] valueArr = {data_temp[10], data_temp[9]};
                                String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                                mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                                mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                                mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压

                                String result = String.format("\nSN号:%s---客户码:%s\n", mSnNumber, mType) +
                                        String.format(getString(R.string.bp_result), mHighValue, mmLowValue, mHeratValue);

                                if (flag) {
                                    tvContent.setText("");
                                    appendContent(result);
                                } else
                                    appendContent("\n历史记录:" + result);
                                flag = false;
                                Flowable.timer(300, TimeUnit.MILLISECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .compose(bindToLifecycle())
                                        .subscribe(new Consumer<Object>() {
                                            @Override
                                            public void accept(Object o) throws Exception {
                                                byte[] data_03 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(3));
                                                refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_03, data_03.length))));


                                                write(mDevice.getAddress(), data_03);
                                            }
                                        });
                            } catch (Exception e) {
                                Log.e("zdw007", e.toString());
                            }
                            break;
                        case 5:
                            Toast.makeText(this, R.string.error_hint, Toast.LENGTH_SHORT);
                            flag = false;
                            break;
                    }
                    data_temp = null;
                    data_temp = new byte[]{};
                }
            }
        } else {
            if (data_temp.length < length) {
                //如果加起来长度还是不够，就直接拼接
                if (data_temp.length + data.length < length) {
                    data_temp = byteMerger(data_temp, data);
                }
                //如果加起来长度刚好够了，
                else if (data_temp.length + data.length == length) {
                    data_temp = byteMerger(data_temp, data);
                    Log.e("zdw007", "length：" + length + "data_temp：" + Arrays.toString(data_temp));
                    switch (length) {
                        case 8:
                            setPreValue(data_temp);
                            break;
                        case 14:
                            try {
                                byte[] valueArr = {data_temp[10], data_temp[9]};
                                String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                                mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                                mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                                mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压

                                String result = String.format("\nSN号:%s---客户码:%s\n", mSnNumber, mType) +
                                        String.format(getString(R.string.bp_result), mHighValue, mmLowValue, mHeratValue);

                                if (flag) {
                                    tvContent.setText("");
                                    appendContent(result);
                                } else
                                    appendContent("\n历史记录:" + result);
                                flag = false;
                                Flowable.timer(300, TimeUnit.MILLISECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .compose(bindToLifecycle())
                                        .subscribe(new Consumer<Object>() {
                                            @Override
                                            public void accept(Object o) throws Exception {
                                                byte[] data_03 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(3));
                                                refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_03, data_03.length))));


                                                write(mDevice.getAddress(), data_03);
                                            }
                                        });
                            } catch (Exception e) {
                                Log.e("zdw007", e.toString());
                            }
                            break;
                        case 5:
                            Toast.makeText(this, R.string.error_hint, Toast.LENGTH_SHORT);
                            flag = false;
                            break;

                    }
                    data_temp = null;
                    data_temp = new byte[]{};
                }
                //如果加起来长度超了，截取下来
                else {
                    int excess_length = data_temp.length + data.length - length;
                    data_temp = byteMerger(data_temp, subBytes(data, 0, data.length - excess_length));
                    setPreValue(data_temp);
                    data_temp = subBytes(data, data.length - excess_length, excess_length);
                }
            } else if (data_temp.length == length) {
                switch (length) {
                    case 8:
                        setPreValue(data_temp);
                        break;
                    case 14:
                        try {
                            byte[] valueArr = {data_temp[10], data_temp[9]};
                            String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                            mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                            mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                            mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压

                            String result = String.format("\nSN号:%s---客户码:%s\n", mSnNumber, mType) +
                                    String.format(getString(R.string.bp_result), mHighValue, mmLowValue, mHeratValue);

                            if (flag) {
                                tvContent.setText("");
                                appendContent(result);
                            } else
                                appendContent("\n历史记录:" + result);
                            flag = false;
                            Flowable.timer(300, TimeUnit.MILLISECONDS)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .compose(bindToLifecycle())
                                    .subscribe(new Consumer<Object>() {
                                        @Override
                                        public void accept(Object o) throws Exception {
                                            byte[] data_03 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(3));
                                            refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_03, data_03.length))));
                                            write(mDevice.getAddress(), data_03);
                                        }
                                    });
                        } catch (Exception e) {
                            Log.e("zdw007", e.toString());
                        }
                        break;
                    case 5:
                        Toast.makeText(this, R.string.error_hint, Toast.LENGTH_SHORT);
                        flag = false;
                        break;

                }
                data_temp = null;
                data_temp = new byte[]{};
            }
        }
    }

    /**
     * 在字节数组中截取指定长度数组
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    /**
     * 得到过程包显示出来
     */
    private void setPreValue(byte[] data) {
        byte[] valueArr = {data[6], data[5]};
        try {
            String strValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(valueArr), 16));//血压 6+5 在转换成10进制
            tvProcess.setText(strValue);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_start:
                connect();
                break;
            case R.id.tv_end_pressure:
                byte[] data_02 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(2));
                refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_02, data_02.length))));

                write(mDevice.getAddress(), data_02);
                break;
            case R.id.tv_start_pressure:
                getResult = false;

                byte[] data_01 = ZHexUtil.hexStringToBytes(ZDataUtil.getSendHex(1));
                refreshLogView("\n写入数据：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_01, data_01.length))));

                write(mDevice.getAddress(), data_01);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDevice != null) {
            ZBleManager.getInstance().disConnectDevice(mDevice.getAddress());
            ZBleManager.getInstance().destroy(mDevice.getAddress());
        }
    }

    @Override
    public void onPermissionsSuccess() {

        initBleSetting();
    }

    private void initBleSetting() {
        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);
        if (mBleManager.isSupportBle()) {
            if (!mBleManager.isBlueOpen()) {
                mBleManager.openBluetooth(this);
            } else {
                if (mDevice != null) {
                    autoConnect(mDevice);
                    return;
                }
                bleScan();
            }
//            String[] names = {"Bioland-BGM", "Bioland", "bioland"};
        } else {
            Toast.makeText(this, R.string.not_support_bluetooth, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPermissionsFail() {
        finish();
    }

    @Override
    public void onBleOpen() {
        Flowable.timer(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        bleScan();
                    }
                });

    }


    private String mMac;
    private boolean isNeedSend = true;//是否需要重写发送
    private boolean isEnableGetValue = false;
    private boolean isAutoConnect = false;
    private boolean isConnect = false;
    private boolean isScanning = false;

    @SuppressLint("CheckResult")
    private void bleScan() {
        if (isScanning) return;
        Flowable.timer(500, TimeUnit.MILLISECONDS)
                .distinct()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBleManager.scan(new IBleScanListener() {
                            @Override
                            public void onScanStarted() {
                                Log.e("zdw", "---onScanStarted-------");
                                isScanning = true;
//                                progress.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onScanCanceled() {
                                Log.e("zdw", "---onScanCanceled-------");
                                isScanning = false;
                                bleScan();
                            }

                            @Override
                            public void onScanStop() {
                                Log.e("zdw", "---onScanStop-------");
                                isScanning = false;
                                bleScan();
                            }

                            @Override
                            public void onDeviceFounded(SearchResult device) {
                                if (device == null) return;
                                if (!device.getName().contains("Bioland-BPM")) return;
                                autoConnect(device);
                            }
                        });
                    }
                });

    }

    /**
     * 自动连接蓝牙
     * Automatic bluetooth connection
     */
    private void autoConnect(SearchResult device) {
        if (null == device) return;
        isAutoConnect = true;
        if (!isConnect) {
            isConnect = true;
            mMac = device.getAddress();
            mDevice = device;
            connect();
        }
    }
}
